package com.mbbb.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mbbb.yygh.common.exception.YyghException;
import com.mbbb.yygh.common.result.R;
import com.mbbb.yygh.common.utils.JwtHelper;
import com.mbbb.yygh.model.user.UserInfo;
import com.mbbb.yygh.user.service.UserInfoService;
import com.mbbb.yygh.user.utils.ConstantPropertiesUtil;
import com.mbbb.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {

    @Autowired
    private UserInfoService userInfoService;


    //回调方法，返回扫码微信的个人信息
    @GetMapping("callback")
    public String callback(String code, String state) {

        //1.得到授权临时票据code
        System.out.println("code:"+code);
        //2.拿着临时票据code和其他数据请求微信的固定接口，返回两个值openid和accessToken
        //HttpClient（没有跨域）
        //https://api.weixin.qq.com/sns/oauth2/access_token --> 微信固定接口
        //① 拼接参数和请求接口，get请求 （不建议这样写）
        /*String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                     "?appid=" + ConstantPropertiesUtil.WX_OPEN_APP_ID +
                     "&secret=" + ConstantPropertiesUtil.WX_OPEN_APP_SECRET +
                     "&code=" + code +
                     "&grant_type=authorization_code";
        //调用接口
        String result = HttpClientUtils.get(url);*/

        //② %s占位符
        try {
            StringBuffer buffer = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                    .append("?appid=%s")
                    .append("&secret=%s")
                    .append("&code=%s")
                    .append("&grant_type=authorization_code");
            //向%s赋值
            String url = String.format(buffer.toString(),
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            //调用接口
            String result = HttpClientUtils.get(url);
            //System.out.println("result = " + result);

            //从返回字符串获取两个值 openid  和  access_token
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //3.拿着openid和access_token请求微信固定地址，得到扫码微信的个人信息
            StringBuffer userBuffer = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?openid=%s")
                    .append("&access_token=%s");
            String userUrl = String.format(userBuffer.toString(), openid, access_token);
            String userResult = HttpClientUtils.get(userUrl);
            //System.out.println("userResult = " + userResult);
            //获取nickname
            JSONObject jsonObject1 = JSONObject.parseObject(userResult);
            String nickname = jsonObject1.getString("nickname");

            //4.把获取的扫码微信的个人信息添加到数据库的user_info表中
            //根据openid查询表中是否存在，如果存在不添加
            UserInfo userInfo = this.selectUserByOpenid(openid);
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            Map<String, String> map = new HashMap<>();

            //5.返回name
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name",name);

            //6.绑定手机号
            //判断userInfo是否有手机号，如果手机号为空，返回openid
            //如果手机号不为空，返回openid值是空字符串
            //前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
            String phone = userInfo.getPhone();
            if (StringUtils.isEmpty(phone)) {
                map.put("openid",openid);
            } else {
                map.put("openid","");
            }

            //7.返回token
            //使用jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token",token);
            //System.out.println(map.get("openid"));
            //8.跳转到前端页面
            return "redirect:http://localhost:3000/weixin/callback?token="
                    +map.get("token")+"&openid="+map.get("openid")
                    +"&name="+URLEncoder.encode(map.get("name"),"UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //根据openid查询表中是否存在
    private UserInfo selectUserByOpenid(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UserInfo userInfo = userInfoService.getOne(wrapper);
        return userInfo;
    }

    //获取微信登录参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public R getLoginParam(HttpSession session) throws UnsupportedEncodingException {
        try {
            Map<String, Object> map = new HashMap<>();
            //生成二维码
            //appId
            map.put("appid",ConstantPropertiesUtil.WX_OPEN_APP_ID);
            //scope
            map.put("scope", "snsapi_login");
            //redirect_uri：扫码后，跳转到本地接口
            //url编码
            String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
            String redirect_uri = URLEncoder.encode(redirectUrl,"UTF-8");
            System.out.println("redirect_uri = " + redirect_uri);
            map.put("redirect_uri",redirect_uri);
            //state
            map.put("state", System.currentTimeMillis()+"");

            return R.ok().data(map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new YyghException(20001,"数据错误");
        }
    }
}
